'use strict';
const db = uniCloud.database();
const _ = db.command;
const $ = db.command.aggregate;

module.exports = {
	//创建订单
	async createOrder(event) {
		try {
			const {
				userId,
				productList,
				addressId,
			} = event;

			// 检查商品库存
			const _ids = productList.map(item => item._id);
			const products = await db.collection('sendgood')
				.where({
					_id: _.in(_ids)
				})
				.get();

			// 构建商品ID到商品的映射
			const productMap = {};
			products.data.forEach(product => {
				productMap[product._id] = product;
			});

			// 检查每个商品的库存
			for (const item of productList) {
				const product = productMap[item._id];

				// 商品不存在
				if (!product) {
					return {
						success: false,
						message: `商品 ${item._id} 不存在`
					};
				}

				// 库存字段存在且小于购买数量（null/undefined表示不限制库存）
				if (product.stock !== null && product.stock !== undefined && product.stock < item.quantity) {
					return {
						success: false,
						message: `商品 ${product.productName || item._id} 库存不足`
					};
				}
			}


			// 计算订单总金额
			let totalAmount = 0;
			for (let item of productList) {
				const product = await db.collection('sendgood').where({
					"_id": item._id
				}).get();
				console.log("product: " + JSON.stringify(product));
				totalAmount += product.data[0].price * item.quantity;
			}
			console.log("-----------------------", totalAmount)
			// 创建订单记录
			const orderId = generateOrderNo()
			const orderResult = await db.collection('order').add({
				orderId: orderId,
				user_id: userId,
				order_time: new Date(),
				order_status: '待支付',
				total_amount: totalAmount,
				address_id: addressId
			});

			console.log("orderResult+++++++++: " + JSON.stringify(orderResult));

			// 扣减商品库存
			for (let item of productList) {
				console.log('item0000000000', item);
				if (item.stock) {
					const stock = await db.collection('sendgood').where({
						"_id": item._id
					}).update({
						stock: _.inc(-item.quantity)
					});
				}

			}

			// 关联订单与商品
			for (let item of productList) {
				const op = await db.collection('orderProducts').add({
					order_id: orderId,
					product_id: item._id,
					quantity: item.quantity
				});

				console.log("op***********: " + JSON.stringify(op));
			}

			return {
				success: true,
				message: '下单成功',
				orderId
			};

		} catch (e) {
			return {
				success: false,
				message: '下单失败'
			}
		} // 从前端获取订单信息

	},

	async add_address({} = address) {
		db.collection('orderAddress').add(address)

	},
	async getOrder(userId) {
		try {
			if (!userId) {
				return {
					code: 400,
					message: '用户ID不能为空'
				};
			}

			// 1. 查询用户所有订单
			const orderResult = await db.collection('order')
				.where({
					user_id: userId
				})
				.get();

			if (!orderResult.data || orderResult.data.length === 0) {
				return {
					code: 404,
					message: '订单不存在'
				};
			}

			// 2. 提取所有订单ID
			const orderIds = orderResult.data.map(order => order.orderId);

			// 3. 批量查询所有订单商品
			const orderProductsResult = await db.collection('orderProducts')
				.where({
					order_id: _.in(orderIds)
				})
				.get();

			// 4. 构建订单ID到商品的映射
			const orderIdToProducts = {};
			orderIds.forEach(orderId => {
				orderIdToProducts[orderId] = orderProductsResult.data
					.filter(op => op.order_id === orderId);
			});
			console.log('orderIdToProducts,订单与商品映射', orderIdToProducts)
			// 5. 提取所有_id
			const _ids = [...new Set(
				orderProductsResult.data.map(op => op.product_id)
			)];
			console.log("_ids.........", _ids)

			// 6. 提取所有address_id
			const addressIds = [...new Set(
				orderResult.data.map(order => order.address_id)
			)];

			// 7. 并发批量查询商品信息、地址信息和支付信息
			const [productInfo, addressInfo, paymentInfo] = await Promise.all([
				db.collection('sendgood').where({
					_id: _.in(_ids)
				}).get(),
				db.collection('orderAddress').where({
					_id: _.in(addressIds)
				}).get(),
				db.collection('Payments').where({
					order_id: _.in(orderIds)
				}).get()
			]);

			// 8. 构建数据映射表
			const productMap = {};
			productInfo.data.forEach(p => {
				productMap[p._id] = {
					id: p._id,
					productName: p.productName || '未知商品',
					price: p.price || 0,
					images: p.images || [],
					description: p.description || '',
					// 添加更多需要的商品字段
				};
			});
			console.log('产品表', productMap);
			const addressMap = {};
			addressInfo.data.forEach(a => {
				addressMap[a._id] = {
					contact: a.contact || '',
					phone: a.phone || '',
					address: a.address || '',
					// 添加更多需要的地址字段
				};
			});
			console.log('地址表', addressMap);
			const paymentMap = {};
			paymentInfo.data.forEach(p => {
				paymentMap[p.order_id] = {
					payment_id: p._id,
					payment_method: p.payment_method || '未知支付方式',
					payment_time: p.payment_time || null,
					status: p.status || '未支付',
					// 添加更多需要的支付信息字段
				};
			});

			// 9. 格式化订单数据
			const orderList = orderResult.data.map(order => {
				const products = orderIdToProducts[order.orderId] || [];
				console.log('products.....', products)
				const formattedProducts = products.map(op => {
					const product = productMap[op.product_id] || {};
					return {
						...product,
						quantity: op.quantity || 0,
						sub_total: (product.price || 0) * (op.quantity || 0)
					};
				});

				return {
					order_id: order.orderId,
					order_time: order.order_time,
					order_status: order.order_status,
					total_amount: order.total_amount,
					address_info: addressMap[order.address_id] || {},
					payment_info: paymentMap[order.orderId] || {},
					products: formattedProducts
				};
			});

			return {
				code: 0,
				data: orderList
			};

		} catch (error) {
			console.error('获取订单列表失败:', error);
			return {
				code: 500,
				message: '获取订单列表失败，请稍后重试'
			};
		}
	},
	/**
	 * @param {Object} search keyword = '',
             category = '',
             minPrice = 0,
             maxPrice = 999999,
             page = 1,
             pageSize = 20,
             groupId='
	 @returns {object} products,senderUser,code
	 */

	async getProduct(search) {
		const {
			keyword = '',
				category = '',
				minPrice = 0,
				maxPrice = 999999,
				page = 1,
				pageSize = 20,
				groupId = ''
		} = search
		try {
			const now = new Date();
			const currentTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(
				now.getHours()
			).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;

			const match = {};

			// 关键词搜索（模糊匹配）
			if (keyword) {
				match.productName = new RegExp(keyword, 'i');
			}

			// 分类筛选
			if (category) {
				match.categorize = category;
			}
			if (groupId) {
				match.groupId = groupId
			}

			// 价格范围筛选
			match.price = _.gte(minPrice).lte(maxPrice);
			match.startDate = _.lte(currentTime)
			match.endDate = _.gte(currentTime)



			// 格式化当前时间为 "YYYY-MM-DD HH:MM:SS"（与数据库中 startDate/endDate 格式保持一致）

			console.log('当前时间（筛选基准）：', currentTime);
			// 1. 获取商品数据
			const res = await db
				.collection('sendgood')
				.where(match)
				.skip((page - 1) * pageSize)
				.limit(pageSize)
				.get();
			console.log('商品列表', res);
			const total = await db.collection('sendgood')
				.where(match)
				.count();

			if (res.data.length > 0) {
				// 2. 转换商品图片URL
				const products = res.data;

				// 3. 提取所有不重复的用户ID
				const userIds = [...new Set(products.map((item) => item.senderUserId))];

				// 4. 批量获取用户信息
				const userRes = await db
					.collection('linli-user')
					.where({
						userId: _.in(userIds)
					})
					.field({
						nicPic: true,
						nicName: true,
						userId: true
					}) // 必须包含userId用于映射
					.get();

				// 5. 创建用户信息映射表（userId -> 用户信息）
				const userMap = new Map();
				userRes.data.forEach((user) => {
					userMap.set(user.userId, {
						nicName: user.nicName,
						nicPic: user.nicPic // 转换用户头像URL
					});
				});
				// 6. 将用户信息映射到商品数据中
				const productsWithUser = products.map((product) => ({
					...product,
					// 添加用户信息，找不到时使用默认值
					userInfo: userMap.get(product.senderUserId) || {
						nicName: '未知用户',
						nicPic: ''
					}
				}));
				const userList = Array.from(userMap).map(([userId, userInfo]) => ({
					userId: userId, // 保留用户ID（可选，用于标识用户）
					...userInfo // 展开用户信息（nicName、nicPic）
				}));
				// 7. 更新数据
				return {
					success: true,
					products: productsWithUser,
					senderUser: userList,
					pagination: {
						page,
						pageSize,
						total: total.total,
						totalPages: Math.ceil(total.total / pageSize)
					}

				}
				//	this.processCategories()
			}
		} catch (error) {
			return {
				code: false,
				errMsg: '调试错误信息，需要删除' + error
			}

		}
	},




}

function generateOrderNo() {
	// 1. 获取当前日期时间，格式化为YYYYMMDDHHmmSS
	const date = new Date();
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	const hours = String(date.getHours()).padStart(2, '0');
	const minutes = String(date.getMinutes()).padStart(2, '0');
	const seconds = String(date.getSeconds()).padStart(2, '0');

	const timeStr = `${year}${month}${day}${hours}${minutes}${seconds}`;

	// 2. 生成3位随机数（000-999）
	const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');

	// 3. 生成1位校验位（增强唯一性，可选）
	const checkStr = timeStr + randomNum;
	let checkCode = 0;
	for (let i = 0; i < checkStr.length; i++) {
		checkCode += parseInt(checkStr[i], 10) * (i + 1);
	}
	const checkBit = (checkCode % 36).toString(36).toUpperCase(); // 0-9A-Z

	// 4. 组合订单号
	return `${timeStr}${randomNum}${checkBit}`;
}